<template>
  <div>
    <!-- 题型标题 -->
    <h1>一、选择题</h1>
    <!-- 题目描述区域 -->
    <p style="font-size: 0.45rem;line-height: 200%;">
      <span style="font-size: 0.6rem;font-weight: bold;">{{ questionParam.qidx + 1 }}.</span>
      <span style="color: grey;"> ({{ questionData.isMultiple? '多选':'单选' }})</span>
      {{ questionData.title }}
    </p>
    <!-- 选项区域 -->
    <div
      v-for="op in quesOptionsMap"
      :key="op.id"
      style="line-height: 200%;font-size: 0.45rem;margin-top: 0.5rem;"
    >
      <button
        class="cf-op-label"
        :class="{['cf-op-label-active']:op.picked}"
        :disabled="!editable"
        @click="doChooseChange(op)"
      >
        {{ op.label }}
      </button>
      {{ op.text }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChooseQuestion',
  props: {
    questionData: {
      type: Object, require: true, default: () => { return {} }
    },
    submitData: {
      type: Object, require: true, default: () => { return {} }
    },
    questionParam: {
      type: Object, require: true, default: () => { return {} }
    },
    editable: {
      type: Boolean, require: false, default: false
    }
  },
  data () {
    return {
      quesOptionsMap: [], // 带选中标签的选项
      lastChooseOp: null // 最近选中的选项
    }
  },
  computed: {
    pickedOps () {
      return this.quesOptionsMap.filter(op => op.picked)
    }
  },
  watch: {

  },
  created () {
    setTimeout(() => {
      let k = 0
      const opNamePool = 'ABCDEFGHIJKLM'
      this.questionData.options.forEach(op => {
        this.quesOptionsMap.push({ id: k, text: op, label: opNamePool.charAt(k++), picked: false })
      })
      // 如果有提交信息，则对选项进行渲染处理
      if (this.submitData) {
        const pickedOps = this.submitData.selectedOptions
        pickedOps.forEach(idx => {
          this.quesOptionsMap[idx].picked = true
          this.lastChooseOp = this.quesOptionsMap[idx]
        })
      }
    }, 0)
  },
  methods: {
    doChooseChange (op) { // 处理选项点击
      if (this.questionData.isMultiple) { // 多选
        op.picked = !op.picked
      } else { // 非多选
        if (this.lastChooseOp) {
          this.lastChooseOp.picked = false
        }
        op.picked = true
      }
      this.lastChooseOp = op
      // 更新提交信息
      this.updateLocalSubmit()
    },
    updateLocalSubmit () { // 更新提交信息
      this.submitData.selectedOptions = this.pickedOps.map(op => op.id)
    }
  }
}
</script>

<style scoped>
.cf-op-label {
  border: 1px solid #c8c9cc;
  background: white;
  display: inline-block;
  height: 0.9rem;
  width: 0.9rem;
  text-align: center;
  color: grey;
  border-radius: 50%;
  cursor: pointer;
}
.cf-op-label-active {
  background: #1989fa;
  border-color: #1989fa;
  color: white;
}
</style>
